<?php
/**
 * ClassName: wait
 * Description:
 * @Author 周昌
 * @Create 2023/11/24 16:18
 */

namespace app;


use epii\server\Args;
use libs\Tool;
use model\ArchivesModel;
use model\MemberInfoModel;
use model\TreatmentModel;
use model\WaitModel;
use service\admin\AdminService;
use service\admin\HospitalService;
use service\admin\MemberService;
use service\admin\MessageService;
use service\admin\ScheduleService;
use service\admin\WaitService;
use service\admin\RoleService;
use think\Db;

class wait extends base
{
    public function init()
    {
        parent::init();
        $this->accessDenied();
    }
    public function index()
    {
        $type=Args::params('type/d');
        if($this->adminInfo['role']==1){
            $this->assign('hospitals',HospitalService::getSelect());
        }
        //筛选
        $this->_as_status = WaitService::waitStatusSelect();
        $this->assign('type',$type);
        $this->adminUiDisplay();
    }

    public function ajax_data()
    {
        $map = [];
        //登录用户权限判断
        $hospital_id=$this->adminInfo['hospital_id'];
        if($hospital_id){
            $map[]=['hospital_id','=',$hospital_id];
        }
        //医生角色登录筛选
        $role=$this->adminInfo['role'];
        if($role==RoleService::$role['doctor']['id']){
//            $map[]=['admin_id','=',$this->adminInfo['id']];
            $map[]=['addtime','>=',strtotime('today')];
            $map[]=['addtime','<=',strtotime('tomorrow')-1];

        }
        $type = Args::params('type');
        if (is_numeric($type)&&$type>=0) {
            $map[] = ['type', "=", $type];
        }
        //状态筛选
        $status = Args::params('status/d');
        if (is_int($status)&&$status>=0) {
            $map[] = ['status', "=", $status];
        }
        //时间筛选
        $start_time=Args::params('start_time');
        if($start_time){
            $start_time=strtotime($start_time);
            $map[]=['addtime','>=',$start_time];
        }
        $end_time=Args::params('end_time');
        if($end_time){
            $end_time=strtotime($end_time);
            $map[]=['addtime','<=',$end_time];
        }

        $name = Args::params('name');
        if ($name) {
            $map[] = ['name', "LIKE", '%' . $name . '%'];
        }

        $hospital_id = Args::params('hospital_id');
        if ($hospital_id) {
            $map[] = ['hospital_id', "=", $hospital_id];
        }
        //将过期排号修改为过期状态
        $res=WaitService::autoCancel();
        echo WaitService::getAjaxData($map);
    }
    //添加
    public function add()
    {
        $type=Args::params('type');
        if(Args::isPost()){
            $data=Args::params('r');
            if($type){
                //治疗
                $this->validate($data,[
                    'phone|手机号'=>'require|mobile',
                    'member_info_id|就诊人'=>'require|integer|>:0',
                    'ward_type|排队房间'=>'require|integer|>=:0',
                ]);
            }else{
                //问诊
                $this->validate($data,[
                    'phone|手机号'=>'require|mobile',
                    'member_info_id|就诊人'=>'require|integer|>:0',
                    'admin_id|医生'=>'require|integer|>:0',
                ]);
            }

            unset($data['phone']);
            $data['type']=$type;
            $res=WaitService::addData($data);
            $res['code']?$this->success($res['msg']):$this->error($res['msg']);
        }
        //获取当前排班医生
        $this->_as_doctors =ScheduleService::getCurrentDoctorSelect();
        $this->_as_type =$type;
        $this->_as_ward_type =WaitService::wardTypeSelect();
        //治疗排队 升房费用
        if($type==1){
            $this->_as_room_fee =(int)TreatmentModel::getValue(['name'=>'升级床位','hospital_id'=>$this->adminInfo['hospital_id']],'price');
        }
        $this->adminUiDisplay();
    }
    //编辑
    public function edit()
    {
        $id = Args::params('id');
        if(Args::isPost()){
            $status=Args::params('status/d');
            //只能取消等待中的排号
            $now_status=WaitModel::getValue(['id'=>$id],'status');
            if($now_status!=WaitService::$wait_status_index['wait']){
                $this->error('只能修改等待中的状态');
            }
           $res= WaitService::status($id,$status);
            $res['code']?$this->success($res['msg']):$this->error($res['msg']);
        }
        $this->_as_info = $id ? WaitModel::getInfo(['id'=>$id]) : [];
        $this->_as_id = $id;
        $this->_as_status = WaitService::waitStatusSelect();
        $this->_as_wait_type = WaitService::waitTypeSelect();
        $this->_as_sex = MemberService::memberSexSelect();
        $this->_as_hospitals = HospitalService::getSelect();

        $this->adminUiDisplay();
    }
    //修改状态
    public function status(){
        $id=Args::params('id/d/1','id,不能为空');
        $status=Args::params('status');
        $res=WaitService::status($id,$status);
        if($res['code']){
            $this->success('成功','refresh');
        }
        $this->error();
    }

    /**
     * @return array|false|string
     * @throws \think\Exception
     * @throws \think\db\exception\PDOException
     * 删除
     */
    public function del()
    {
        $id = Args::params('id');
        //todo 判断该事项下是否已经有床位，无则可以删除
        $res = WaitService::del($id);
        if ($res['code']) {
            $this->success($res['msg'],'refresh');
        } else {
            $this->error($res['msg']);
        }
    }
    //根据手机号获取排号人信息
    public function getMemberInfo(){
        $phone=Args::params('phone');
        $res=MemberService::getInfoByPhone($phone,'','id,member_id,name');
        if(empty($res)){
            exit(json_encode(Tool::Error('手机号尚未注册会员')));
        }
        exit(json_encode(Tool::Success('成功',$res['info'])));
    }
    //从问诊自动转治疗排号,同时修改问诊排号状态为已结束
    public function atuoAdd()
    {
        $wait_id=Args::params('wait_id/d');
        $wait_info=WaitModel::getInfo(['id'=>$wait_id]);
        //判断该患者是否在治疗排队中
        $where=[
            'case_id'=>$wait_info['case_id'],
            'type'=>WaitService::$wait_type_index['treatment'],
        ];
        $wait_res=WaitModel::getInfo($where);
        if($wait_res){
            return $this->error('已在排号中');
        }
        $wait_info['type']=WaitService::$wait_type_index['treatment'];
        $wait_info['num']=WaitService::getNum($wait_info['ward_type'],$wait_info['is_vip'],$wait_info['type']);
        $wait_info['status']=WaitService::$wait_status_index['wait'];
        $wait_info['addtime']=time();
        $wait_info['update_time']=time();
        unset($wait_info['id']);
        unset($wait_info['admin_id']);
        Db::startTrans();
        try {
            $res=WaitService::add($wait_info);
            $result=WaitService::edit($wait_id,['status'=>WaitService::$wait_status_index['end'],'update_time'=>time()]);
            //问诊结束成功 消息
            $message_res=MessageService::addMessage($wait_info['member_id'],MessageService::$message_type_index['ask'],null,null,$wait_info['archives_id']);
            if($message_res['code']==0){
                Db::rollback();
                return Tool::Error('签到消息添加失败');
            }
            //签到普通病床 自动分配床位
            if(!$wait_info['ward_type']){
                $w_res=WaitService::autoBed($res['data']['id']);
                if($w_res['code']==0){
                    Db::rollback();
                    return Tool::Error($w_res['msg']);
                }
            }
            if($res['code']==0||$result['code']==0){
                Db::rollback();
                return $this->error('治疗排队失败');
            }else{
                Db::commit();
                return $this->success('治疗排队成功');
            }

        }catch (\Exception $exception){
            Db::rollback();
            return $this->error('治疗排队失败');
        }

        $res['code']?$this->success($res['msg']):$this->error($res['msg']);
    }

}